package com.roger.exercise;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class RogerDBService {

	private RogerSQLiteHelper sqliteHelper;

	public RogerDBService(Context context) {
		sqliteHelper = new RogerSQLiteHelper(context);
	}

	public void save(RogerInfo rogerInfo) {
		SQLiteDatabase db = null;
		try {
			db = sqliteHelper.getWritableDatabase();
			db.execSQL(
					"insert into roger_info (id,file_name,file_content) values(?,?,?)",
					new Object[] { rogerInfo.getId(), rogerInfo.getFileName(),
							rogerInfo.getFileContent() });
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (db != null) {
				db.close();
			}
		}
	}

	public RogerInfo findById(int id) {
		SQLiteDatabase db = null;
		RogerInfo rogerInfo = null;
		try {
			db = sqliteHelper.getReadableDatabase();
			Cursor cursor = db.rawQuery("select * from roger_info where id=?",
					new String[] { id + "" });
			rogerInfo = new RogerInfo();
			while (cursor.moveToNext()) {
				rogerInfo.setId(cursor.getInt(cursor.getColumnIndex("id")));
				rogerInfo.setFileName(cursor.getString(cursor
						.getColumnIndex("file_name")));
				rogerInfo.setFileContent(cursor.getString(cursor
						.getColumnIndex("file_content")));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (db != null) {
				db.close();
			}
		}
		return rogerInfo;
	}
}
